<?php

include_once('logic/action/Action.php');
include_once('logic/view/upload_view.php');

class UploadAction extends Action
{
	public function perform()
	{

		$View = new UploadView();
		$Tags = new TagsDAO();
		$Photos = new PhotosDAO();

		if (Session::getSessionVar ("logged_in") == 'true')
		{
			$View->setParam('_user_logged_in', 'true');
			// check if there was a post
			if (HttpRequest::getRequest('form_posted') == 'posted')
			{
				$valid = true;

				// get values
				$file = trim(HttpRequest::getRequest('file'));
				$title = trim(HttpRequest::getRequest('title'));
				$description = trim(HttpRequest::getRequest('description'));
				$date = trim(HttpRequest::getRequest('date'));
				$tags = HttpRequest::getRequest('tags');

				// title empty
				if (Validator::isEmpty($title))
				{
					$View->setParam('_title_empty_error', 'true');
					$valid = false;
				}

				// date empty
				if (Validator::isEmpty($date))
				{
					$View->setParam('_date_empty_error', 'true');
					$valid = false;
				}

				// date format is wrong
				if (!Validator::isDate($date))
				{
					$View->setParam('_date_format_error', 'true');
					$valid = false;
				}

				$file_name = $_FILES['file']['name'];
				$file_type = $_FILES['file']['type'];
				$file_size = $_FILES['file']['size'];
				$file_data = $_FILES['file']['tmp_name'];

				// if file is empty
				if (Validator::isEmpty($file_name))
				{
					$View->setParam('_file_empty_error', 'true');
					$valid = false;
				}

				if ($file_size == 0)
				{
					$View->setParam('_zero_sized_file', 'true');
					$valid = false;
				}

				// fill back common things
				$View->setParam('_file', $file);
				$View->setParam('_title', $title);
				$View->setParam('_description', $description);
				$View->setParam('_date', $date);

				if ($valid)
				{
					$file = fopen($file_data, 'r');
					$data = fread($file, $file_size);
					fclose($file);

					// add photo to db
					$photoId = $Photos->addPhoto($title,
						$file_type,
						$file_size,
						$data,
						$date,
						$description);

					// insert the tags
					$tagsArray = explode(',', $tags);
					$filteredTags = "";
					foreach ($tagsArray as $tag)
					{
						$tmp = trim($tag);
						if ($tmp != "")
						{
							$Tags->addTag($photoId, trim($tmp));

							// build new tag list (filter out separators)
							if ($filteredTags != '') $filteredTags .= ', ';
							$filteredTags .= $tmp;
						}
					}
					$View->setParam('_tags', $filteredTags);


					$View->setParam('_file_uploaded', 'true');
				}
			}
		} else {
			$View->setParam('_user_logged_in', 'false');
		}

		parent::setCommonParams($View);

		$View->display();
	}
}

?>
